if(NOT CUDAToolkit_ROOT)
  if(NOT CUDA_ROOT)
    set(CUDA_ROOT $ENV{CUDA_ROOT})
  endif()
  if(CUDA_ROOT)
    set(CUDAToolkit_ROOT ${CUDA_ROOT})
  endif()
endif()

if(KOKKOS_CXX_HOST_COMPILER_ID STREQUAL NVHPC AND CMAKE_VERSION VERSION_LESS "3.20.1")
  message(FATAL_ERROR "Using NVHPC as host compiler requires at least CMake 3.20.1")
endif()

set(TPL_CUDA_LIBRARIES "")
if(KOKKOS_ENABLE_COMPILE_AS_CMAKE_LANGUAGE)
  set(TPL_CUDA_LIBRARIES CUDA::cuda_driver)
else()
  set(TPL_CUDA_LIBRARIES CUDA::cuda_driver CUDA::cudart)
endif()

if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17.0")
  find_package(CUDAToolkit REQUIRED)
  kokkos_create_imported_tpl(CUDA INTERFACE LINK_LIBRARIES ${TPL_CUDA_LIBRARIES})
  kokkos_export_cmake_tpl(CUDAToolkit REQUIRED)
else()
  include(${CMAKE_CURRENT_LIST_DIR}/CudaToolkit.cmake)

  if(TARGET CUDA::cudart)
    set(FOUND_CUDART TRUE)
    kokkos_export_imported_tpl(CUDA::cudart)
  else()
    set(FOUND_CUDART FALSE)
  endif()

  if(TARGET CUDA::cuda_driver)
    set(FOUND_CUDA_DRIVER TRUE)
    kokkos_export_imported_tpl(CUDA::cuda_driver)
  else()
    set(FOUND_CUDA_DRIVER FALSE)
  endif()

  include(FindPackageHandleStandardArgs)
  find_package_handle_standard_args(TPLCUDA ${DEFAULT_MSG} FOUND_CUDA_DRIVER FOUND_CUDART)
  if(FOUND_CUDA_DRIVER AND FOUND_CUDART)
    kokkos_create_imported_tpl(CUDA INTERFACE LINK_LIBRARIES ${TPL_CUDA_LIBRARIES})
  endif()
endif()
